/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cassandrawindow;

import count.FraudCountByGuid;
import count.FraudGuidInSecRangeResult;
import countdate.FraudCountByGuidInDate;
import countdate.FraudGuidInDateRangeResult;
import countdatebanner.FraudCountGuidBannerInDate;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.log4j.xml.DOMConfigurator;
import util.ConfigUtil;

public class HandleFraudClickByDayBanner {
    public static final String KEYSPACE                             =   "AdsData";
    public static final String ColumFamly                           =   "BannerViewCountCf";
    public static final String ColumFamlyBannerClickCountCf         =   "BannerClickCountCf";
    public static final String ColumFamlyBannerViewCountCf          =   "BannerViewCountCf";

    public static final String ColumFamlyCampaignClickCountCf       =   "CampaignCountCf";
    public static final String ColumFamlyCampaignViewCountCf        =   "CampaignViewCountCf";

    public static final String ColumFamlyCampaignIPCountCf          =   "CampaignIpCountCf";

    public static final String SuperColumFamlyCampaignGuidClick     =   "Guid_Click_Super_Cf";
    
    public static final String ColumFamlyGuidDataContentBanneridData    =   "GuidDate_Content_Bannerid_DataCF";
    
    public static final String FRAUDCLICKKEYSPACE                       =   "FraudKs";

    public static long checkFraudClickbyDayBanner   =   0;
    
    public void handleData() throws ParseException, InterruptedException, IOException
    {
        long first_time = System.currentTimeMillis();
        int count = 0;
        try{
            CassandraAction cassAct = new CassandraAction(ACCOUNT.CLUSTERNAME ,ACCOUNT.URL, ACCOUNT.PORT);
            cassAct.initReadWirte(FRAUDCLICKKEYSPACE);
            MysqlDataManager mysql = new MysqlDataManager();
            //mysql.getCountFraudClickByBannerIDAndDay(1004352, "2012-07-07");
            //mysql.updateFraudClick(2035, "2012-07-07");
            // start time
            ConfigUtil.setPathConfig("/home/bigdata/cpc/properties/conf.properties");
            DOMConfigurator.configure("/home/bigdata/cpc/properties/log4j.xml");
            //ConfigUtil.setPathConfig("E:\\config_fraud_click\\conf.properties");
            //DOMConfigurator.configure("E:\\config_fraud_click\\log4j.xml");     
            String currentDate = HandleDataTableDomainDate.handleDate();//2012-07-24
            //String currentDate = TimeUtil.getCurrentTimeInString();//2012-07-24
            //String currentDate = CONSTANT.Date;
            String[] arrTime = new String[3];
            arrTime = removeSpaces(currentDate).split("-");
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.set(Integer.valueOf(arrTime[0]), Integer.valueOf(arrTime[1])-1, Integer.valueOf(arrTime[2]), 23, 59, 55);
            endCalendar.set(Calendar.MILLISECOND, 0);
                        
            List<FraudGuidInDateRangeResult> fraudGuidInSecRangeResults = new FraudCountGuidBannerInDate().countFraudGuidInDateSlice(10L, endCalendar.getTime());
            
            Debug.println("so guidid khong hop le theo banner:" +fraudGuidInSecRangeResults.size());
            Iterator it = fraudGuidInSecRangeResults.iterator();
            //String insertDate = "2012-07-07";
            
            while(it.hasNext())
            {
                FraudGuidInDateRangeResult value = (FraudGuidInDateRangeResult) it.next();                
                //System.out.println(value.getGuid());
                //System.out.println(value.getDateString());
                String str = cassAct.getFraudClickDay(value.getGuid()+"_"+value.getDateString(),ColumFamlyGuidDataContentBanneridData, currentDate);
                //check null
                if(str.length() > 1)
                {
                    String valInsert = str.substring(0, (str.length()-1));
                    mysql.insertFraudClick(valInsert);
                }
            }

        } catch (Exception ex)
        {
           Debug.println("exception sucess rule 3:"+ex.getMessage());
        }
        long last_time = System.currentTimeMillis();        
        Debug.println("sucess rule 3");
        Debug.println("Thoi gian chay  :" +(last_time-first_time));
    }

  public static String removeSpaces(String s) {
          StringTokenizer st = new StringTokenizer(s," ",false);
          String t="";
          while (st.hasMoreElements()) t += st.nextElement();
          return t;
        }

    /*
     * Lay thoi gian tu 6h sang ngay hom truoc toi 5h59 sang ngay hom sau
     * Coi la 1 ngay
     */
    public String handleDate()
    {
        String retDate = "";//2012-07-24
        String date = TimeUtil.getCurrentTimeInStringForLog();//yyyy/MM/dd H:mm:ss
        String[] arrTime = new String[2];
        String[] firstArrTime = new String[3];
        String[] secondArrTime = new String[3];

        arrTime = date.split(" ");
        firstArrTime    = arrTime[1].split(":");
        secondArrTime   = arrTime[0].split("-");
        //init checkDate if trigger from 0h -> 6h
        if(checkFraudClickbyDayBanner == 0)
        {
            checkFraudClickbyDayBanner = TimeUtil.getCurrentTime();
        }

        if(Integer.valueOf(firstArrTime[0]) >= 6 && Integer.valueOf(firstArrTime[0]) <= 23)
        {
            checkFraudClickbyDayBanner = TimeUtil.getCurrentTime();
            retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+secondArrTime[2];
        } else if (Integer.valueOf(firstArrTime[0]) >= 0 && Integer.valueOf(firstArrTime[0]) < 6 && TimeUtil.getCurrentTime() >= checkFraudClickbyDayBanner)
        {
            Debug.println(date + "_" + TimeUtil.getCurrentTime() + "_" + checkFraudClickbyDayBanner);
            int day = Integer.valueOf(secondArrTime[2]) - 1;
            retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+String.valueOf(day);
        }
        return retDate;
    }
}
